import os
import configparser
import json
import time
import hashlib
import win32api
import numpy as np
from scipy import interpolate
import shutil

from PyQt5.QtWidgets import *
from PyQt5.QtGui import *
from PyQt5.QtCore import *

from AddPddDialog import PddDialog
from AddOarDialog import OarDialog
from ChartDeal import ChartDealWidget
from MultiLineAnalyseDialog import MultiLineDialog
# from ChartDeal import ChartDealWidget
from ui.Project import Ui_DockWidget
from ui.createProject import Ui_Dialog

class ProjectCreateDialog(QDialog, Ui_Dialog):
    def __init__(self, parent = None, save_path=''):
        super(QDialog, self).__init__(parent)
        self.setupUi(self)
        self.setWindowIcon(QIcon(':icons/images_rc/project.png'))
        self.pushButton_open.clicked.connect(self.openDirectory)
        self.save_path = save_path
        self.proj_name = 'example'
        self.proj_path = save_path+'/'+self.proj_name
        self.lineEdit_path.setText(self.save_path)
        self.lineEdit_name.setText(self.proj_name)
        self.pushButton_getTime.clicked.connect(self.getTime)

    def openDirectory(self):
        fi = QFileDialog(self)
        fi.setWindowTitle("选择项目保存的文件夹")
        fi.setDirectory(self.save_path)
        fi.setFileMode(QFileDialog.Directory)
        if fi.exec():
            filename = fi.selectedFiles()
            if filename:
                self.lineEdit_path.setText(filename[0].replace('/','\\'))

    def getTime(self):
        _time      = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime())
        self.lineEdit_time.setText(_time)

    def addProjectFile(self,path,name,operator,address,_time,remark):
        """项目信息文件

        name:     项目名称
        operator: 检测人员
        address:  检测地址
        _time:    检测时间
        """
        config = configparser.RawConfigParser()
        # 添加project选项
        config.add_section('project')
        config.set('project', 'name', name)
        config.set('project', 'operator', operator)
        config.set('project', 'address', address)
        config.set('project', 'time', _time)
        config.set('project', 'remark', remark)
        # 文件名称
        file = r'%s\%s.proj' % (path,name)
        # 写入并保存文件到当前项目文件夹下
        with open(file, 'w') as configfile:
            config.write(configfile)

    def accept(self):
        """确认创建"""
        self.proj_name = self.lineEdit_name.text()
        self.save_path = self.lineEdit_path.text()
        self.proj_path = self.save_path+'\\'+self.proj_name
        if os.path.exists(self.proj_path):
            QMessageBox.information(self,'提示','项目已存在!',QMessageBox.Yes)
        else:
            os.makedirs(self.proj_path)
            os.makedirs(self.proj_path+'\\data')
            os.makedirs(self.proj_path+'\\task')
            self.addProjectFile(self.proj_path,
                                self.proj_name,
                                self.lineEdit_person.text(),
                                self.lineEdit_addr.text(),
                                self.lineEdit_time.text(),
                                self.textEdit_remark.toPlainText(),
                                )
            QDialog.accept(self)

class TreeWidget(QTreeWidget):
    dataSignal = pyqtSignal(dict,list)
    addTaskSignal = pyqtSignal(str)
    signalClickTask= pyqtSignal(dict)
    signal= pyqtSignal(dict)
    signal_showChart = pyqtSignal(str)
    def __init__(self, parent = None, save_path=''):
        super(TreeWidget, self).__init__(parent)
        self.setColumnCount(1)
        self.setMinimumWidth(500)
        # 设置多选
        self.setSelectionMode(QAbstractItemView.ExtendedSelection)
        # 取消拖拽功能
        self.setAcceptDrops(False)
        # 右键菜单设置
        self.setContextMenuPolicy(Qt.CustomContextMenu)
        self.customContextMenuRequested.connect(self.rightMenu)
        # 设置可拖拽
        # 设置显示将要被放置的位置
        # self.setDropIndicatorShown(True)
        # 设置拖放模式为移动项目，否则为复制项目
        self.setAcceptDrops(True)
        self.setDragEnabled(True)
        self.setDragDropMode(QAbstractItemView.InternalMove)
        # 拖拽功能
        self.draggedItem = None
        # self.setAttribute(Qt.WA_PaintOutsidePaintEvent)
        # pdd oar 对话框
        self.pddDlg = PddDialog()
        self.oarDlg = OarDialog()
        # self.chartDealDlg = ChartDealWidget()
        # self.chartDealDlg.setWindowIcon(QIcon(':icons/images_rc/chart.png'))
        # self.multiChartDlg= MultiLineDialog()
        # self.multiChartDlg.setWindowIcon(QIcon(':icons/images_rc/multi-chart.png'))

        self.clicked.connect(self.Clicked)
        self.doubleClicked.connect(self.on_doubleClicked)

        self.projectItems = {}
        self.proj_save_path = save_path
        self.proj_name = ''

        self.save_path = save_path
        self.projects = {}
        self.createProjectDlg = ProjectCreateDialog(save_path=self.save_path)

        self.header_path = ''
        # self.clicked_path= ''
        self.selectItem = ''
        self.rootItem = ''
        self.setHeaderLabel('')
        self.icon = {
            'project':QIcon(':icons/images_rc/project.png'),
            'task':QIcon(':icons/images_rc/task.png'),
            'task_green':QIcon(':icons/images_rc/task_green.png'),
            'data':QIcon(':icons/images_rc/data.png'),
            'pdd':QIcon(':icons/images_rc/pdd.png'),
            'oar':QIcon(':icons/images_rc/oar.png'),
        }
        self.timerRunTask = QTimer()
        self.timerRunTask.timeout.connect(self.runTask)
        self.timerRunTask.start(500)
        self.run_task_flag = False
        self.run_task_status = False
        self.taskItems = []
        self.tasks = []
        # 正在执行的任务item
        self.runTaskItem = None
        # 添加任务状态
        self.add_task_action_enable = False

    def rightMenu(self):
        self.menu = QMenu()
        self.showProjInfoAction = QAction("&查询项目信息",triggered=self.showProjInfo)
        self.closeProjectAction = QAction("&关闭项目",triggered=self.closeProject)
        self.deleteProjectAction = QAction("&删除项目",triggered=self.deleteProject)
        self.showChartAction = QAction("&单曲线分析",triggered=self.showChart)
        self.multiChartShowAction = QAction("&多曲线分析",triggered=self.multiChartShow)
        self.exportMultiExcelAction= QAction("&导出excel",triggered=self.exportMultiExcel)
        self.addPddAction = QAction("&添加PDD任务",triggered=self.addPddTask)
        self.addOarAction = QAction("&添加OAR任务",triggered=self.addOarTask)
        self.oarHalfDataToOneAction = QAction("&OAR半边数据合并",triggered=self.oarHalfDataToOne)
        if self.add_task_action_enable:
            self.addPddAction.setEnabled(True)
            self.addOarAction.setEnabled(True)
        else:
            self.addPddAction.setEnabled(False)
            self.addOarAction.setEnabled(False)
        self.deleteSelectsAction = QAction("&删除所选文件",triggered=self.deleteSelected)
        self.openExplorerAction= QAction("&打开文件所在位置",triggered=self.openExplorer)
        self.tmrChangeAction = QAction("&tmr转换",triggered=self.tmrChange)
        self.tmrOpenAction = QAction("&tmr分析",triggered=self.tmrOpen)
        self.menu.addAction(self.showProjInfoAction)
        # self.menu.addAction(self.closeProjectAction)
        # self.menu.addAction(self.deleteProjectAction)
        self.menu.addAction(self.showChartAction)
        self.menu.addAction(self.multiChartShowAction)
        self.menu.addAction(self.exportMultiExcelAction)
        self.menu.addAction(self.oarHalfDataToOneAction)
        # self.menu.addAction(self.addPddAction)
        # self.menu.addAction(self.addOarAction)
        # self.menu.addAction(self.chartDealAction)
        self.menu.addAction(self.deleteSelectsAction)
        self.menu.addAction(self.openExplorerAction)
        self.menu.addAction(self.tmrChangeAction)
        self.menu.addAction(self.tmrOpenAction)
        self.menu.exec(QCursor.pos())

    def Clicked(self, item):
        self.selectItem = self.selectedItems()[0]
        # 查询根节点, 并显示当前点击目录
        rootItem = self.selectedItems()[0]
        self.header_path = rootItem.text(0)
        while rootItem.parent():
            rootItem = rootItem.parent()
            self.header_path = rootItem.text(0) +'\\' + self.header_path
        # self.clicked_path = self.save_path+'\\'+self.header_path
        # self.item_path =
        # 根目录
        self.rootItem = rootItem
        # 当前点击目录
        self.setHeaderLabel(self.header_path)
        # 项目名称
        proj_name = rootItem.text(0)
        # 更新项目路径
        self.setPath(proj_name)
        # 更新右键菜单功能
        if self.header_path.endswith('task'):
            self.add_task_action_enable = True
        else:
            self.add_task_action_enable = False
        # 显示示意图信号
        if self.currentItem().text(0).endswith('.t'):
            task = self.readTaskFile(self.getItemPath(self.currentItem()))
            self.signalClickTask.emit(task)

    def dropEvent(self, event):
        droppedIndex = self.indexAt(event.pos())
        if not droppedIndex.isValid():
            return
        for dragged_item in self.selectedItems():
            # dragged_parent: 拖拽节点的父节点
            dragged_parent = dragged_item.parent()
            if dragged_parent:
                # 拖拽目的地位置对应的item
                item = self.itemAt(event.pos())
                if item:
                    item_parent = item.parent()
                    if item_parent:
                        # 获取路径
                        dragged_item_path = self.getItemPath(dragged_item)
                        item_path         = self.getItemPath(item)
                        item_parent_path  = self.getItemPath(item_parent)
                        # 同一个父节点下移动,只变化节点的顺序
                        if item_parent == dragged_parent:
                            dragged_parent.removeChild(dragged_item)
                            dragged_parent.insertChild(droppedIndex.row(), dragged_item)
                        # 不同父节点下移动节点位置，并移动节点对应的文件
                    else:
                        if item_parent.text(0) == dragged_parent.text(0):
                            # 父节点名称相同, task文件移动到task文件下, data文件移动到data文件下
                            # 移动.t文件
                            if dragged_item_path.endswith('.t'):
                                if item_path.endswith('task'):
                                    # item移动,移动文件
                                    dragged_parent.removeChild(dragged_item)
                                    item.insertChild(item.childCount(), dragged_item)
                                    if os.path.isfile(dragged_item_path) and os.path.isdir(item_path):
                                        shutil.move(dragged_item_path, item_path)
                                    if item_path.endswith('.t'):
                                        # item移动,移动文件
                                        dragged_parent.removeChild(dragged_item)
                                        item_parent.insertChild(item_parent.childCount(), dragged_item)
                                        if os.path.isfile(dragged_item_path) and os.path.isdir(item_parent_path):
                                            shutil.move(dragged_item_path, item_parent_path)
                                # 移动.d文件
                                if dragged_item_path.endswith('.d'):
                                    if item_path.endswith('data'):
                                        # item移动,移动文件
                                        dragged_parent.removeChild(dragged_item)
                                        item.insertChild(item.childCount(), dragged_item)
                                        if os.path.isfile(dragged_item_path) and os.path.isdir(item_path):
                                            shutil.move(dragged_item_path, item_path)
                                    if item_path.endswith('.d'):
                                        # item移动,移动文件
                                        dragged_parent.removeChild(dragged_item)
                                        item_parent.insertChild(item_parent.childCount(), dragged_item)
                                        if os.path.isfile(dragged_item_path) and os.path.isdir(item_parent_path):
                                            shutil.move(dragged_item_path, item_parent_path)

    def on_doubleClicked(self):
        self.showChart()
        self.showTask()

    def showChart(self):
        file_path = self.getItemPath(self.currentItem())
        if file_path:
            if os.path.isfile(file_path):
                if file_path.endswith('.d'):
                    # self.signal_showChart.emit(file_path)
                    self.chartDealDlg = ChartDealWidget()
                    self.chartDealDlg.setWindowIcon(QIcon(':icons/images_rc/chart.png'))
                    self.chartDealDlg.setWindowTitle(file_path)
                    # self.chartDealDlg
                    self.chartDealDlg.showOneLine(file_path)
                    self.chartDealDlg.show()

    def showTask(self):
        """修改任务
        1、修改后生成一个新的配置文件
        2、删除修改前的文件
        3、新的配置文件就是最新修改的文件，并修改界面显示中item的名称为新配置文件的名称
        """
        file_path = None
        if self.currentItem:
            file_path = self.getItemPath(self.currentItem())
        if file_path:
            if os.path.isfile(file_path):
                if file_path.endswith('.t'):
                    task = self.readTaskFile(file_path)
                    if task:
                        try:
                            if task['type'] == 'PDD':
                                self.pddDlg.load_config(task)
                                self.pddDlg.setWindowTitle('PDD任务显示/修改')
                                if self.pddDlg.exec() == QDialog.Accepted:
                                    conf = self.pddDlg.conf
                                    file_name = self.addTaskFile(conf)
                                    self.currentItem().setText(0, file_name)
                                    os.remove(file_path)
                            if task['type'] == 'OAR':
                                self.oarDlg.load_config(task)
                                self.oarDlg.setWindowTitle('OAR任务显示/修改')
                                if self.oarDlg.exec() == QDialog.Accepted:
                                    conf = self.oarDlg.conf
                                    # 添加新文件
                                    file_name = self.addTaskFile(conf)
                                    self.currentItem().setText(0, file_name)
                                    # 删除原文件
                                    os.remove(file_path)
                        except:
                            QMessageBox.information(self, "提示", "文件数据格式错误，无法打开", QMessageBox.Yes)
                    else:
                        QMessageBox.information(self, "提示", "文件数据格式错误，无法打开", QMessageBox.Yes)

    def readTaskFile(self, file_path=''):
        """读取任务文件中数据 """
        try:
            config = configparser.ConfigParser()
            config.read(file_path)
            condition = dict(config['condition'])
            if condition['type'] == "OAR":
                condition['road'] = json.loads(condition['road'])
                condition['pos_x'] = json.loads(condition['pos_x'])
                condition['pos_y'] = json.loads(condition['pos_y'])
                condition['step_x'] = json.loads(condition['step_x'])
                condition['step_y'] = json.loads(condition['step_y'])
            if condition['type'] == "PDD":
                condition['road'] = json.loads(condition['road'])
                condition['pos'] = json.loads(condition['pos'])
                condition['step'] = json.loads(condition['step'])
                return condition
        except:
            return False

    def openExplorer(self):
        """打开项目文件夹管理"""
        item = self.currentItem()
        if item:
            path = self.getItemPath(item)
            QProcess.startDetached('explorer.exe /select,"%s"'%(path.replace('/','\\')))

    def setPath(self,proj_name):
        # 项目保存位置
        self.save_path = r"%s\\projects"%os.getcwd()
        # 当前项目名称
        self.proj_name = proj_name
        # 当前项目路径
        self.proj_path = r"%s\\%s"%(self.save_path, self.proj_name)
        # 当前项目任务路径
        self.task_path = r"%s\\task"%self.proj_path
        # 当前项目数据路径
        self.data_path = r"%s\\data"%self.proj_path

    def getSelectsFilePath(self):
        files = []
        for s in self.selectedItems():
            files.append(self.getItemPath(s))
        return files

    def showProjInfo(self):
        try:
            rootItem = self.getRootItem(self.currentItem())
            file_path = self.projects[rootItem.text(0)]['proj_file']
            config = configparser.ConfigParser()
            config.read(file_path)
            project= config['project']
            info = \
                '项目名称：%s\r\n'%project['name']+\
                '检测人员：%s\r\n'%project['operator']+\
                '检测地点：%s\r\n'%project['address']+\
                '检测时间：%s\r\n'%project['time']+\
                '备注：\r\n%s\r\n'%project['remark']
            QMessageBox.information(self,
                                    '项目信息',
                                    info,
                                    QMessageBox.Yes)
        except:
            QMessageBox.information(self,
                                    '错误',
                                    "项目信息不存在，无法查询",
                                    QMessageBox.Yes)

    def oarHalfDataToOne(self):
        if not len(self.getSelectsFilePath()) == 2:
            QMessageBox.warning(self, '警告', '请选择两个分别包含left和right的文件!', QMessageBox.Yes)
            return
        left = None
        right = None
        item = None
        for f in self.getSelectsFilePath():
            if f.endswith('.d'):
                d = self.readDataFile(f)
                if not d:
                    QMessageBox.warning(self, '警告', '数据读取失败\r\n%s'%f, QMessageBox.Yes)
                    return
                cond = d['condition']
                half = cond['half'] if 'half' in cond else ''
                if not half:
                    QMessageBox.warning(self, '警告', '请选择包含left和right的两个文件', QMessageBox.Yes)
                    return
                if half == 'left':
                    left = d
                if half == 'right':
                    right = d
        if left and right:
            conf_left = left['condition']
            conf_right = right['condition']
            if not conf_left['direction'] == conf_right['direction']:
                QMessageBox.warning(self, '警告', '两个文件的方向不一致', QMessageBox.Yes)
                return
            if not conf_left['type'] == conf_right['type']:
                QMessageBox.warning(self, '警告', '两个文件的类型不一致', QMessageBox.Yes)
                return
            if not conf_left['power'] == conf_right['power']:
                QMessageBox.warning(self, '警告', '两个文件的能量不一致', QMessageBox.Yes)
                return
            if not conf_left['angle'] == conf_right['angle']:
                QMessageBox.warning(self, '警告', '两个文件的摆位方向不一致', QMessageBox.Yes)
                return
            if not conf_left['ray_size_x'] == conf_right['ray_size_x']:
                QMessageBox.warning(self, '警告', '两个文件的射野大小不一致', QMessageBox.Yes)
                return
            if not conf_left['ray_size_y'] == conf_right['ray_size_y']:
                QMessageBox.warning(self, '警告', '两个文件的射野大小不一致', QMessageBox.Yes)
                return
            if not conf_left['deepth'] == conf_right['deepth']:
                QMessageBox.warning(self, '警告', '两个文件的深度不一致', QMessageBox.Yes)
                return
            if not conf_left['ssd'] == conf_right['ssd']:
                QMessageBox.warning(self, '警告', '两个文件的源皮距不一致', QMessageBox.Yes)
                return
            data = left['data']+right['data']
            float_data = [[float(x) for x in d] for d in data]
            left['condition']['half'] = ''
            self.addDataFileToCurrentItem(condition=left['condition'], data=float_data)

    def addDataFileToCurrentItem(self, condition={},data=[]):
        """写入数据到项目文件中

        filename:文件名
        data:  测量数据 [[x,y,z,tm,ts],[x,y,z,tm,ts],....]
        condition:  测量条件 {"type":"PDD"}
        """
        config = configparser.RawConfigParser()
        # config = self.raw_config
        # 添加condition选项
        config.add_section('condition')
        _time      = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime())
        config.set('condition', 'time', _time)
        for k in condition.keys():
            config.set('condition', str(k), str(condition[k]))
        # 添加data选项
        config.add_section('data')
        for i in range(0,len(data)):
            config.set('data', str(i), str(data[i]))
        # 文件名称
        t = condition
        ti = time.strftime("%Y%m%d%H%M%S", time.localtime())
        _hash = self.get_hashlib()
        angle = t['angle'] if 'angle' in t else ''
        half = t['half'] if 'half' in t else ''
        file_name= '%s_%s_%s_%s_%s_%s_%s_%s.d'%(
            t['ray_type'],
            t['type'],
            t['power'],
            t['ray_size_x']+'x'+t['ray_size_y'],
            t['direction'].replace('->','').replace('cm','').replace('Mev',''),
            angle,
            half,
            ti,)
        # path = r'%s\%s' % (self.data_path, file_name)
        # 保存数据文件到正在执行的item对应的项目下
        if self.currentItem():
            item = self.getRootItem(self.currentItem())
            task_path = self.projects[item.text(0)]['data_path']
            path = r'%s\%s' % (task_path, file_name)
            # 写入并保存文件到当前项目文件夹下
            with open(path, 'w') as configfile:
                config.write(configfile)
            self.addItem(file_name)
        else:
            QMessageBox.warning(self, "错误", "请选择项目再添加任务", QMessageBox.Yes)

    def multiChartShow(self):
        x_list = []
        y_list = []
        f_list = []
        for f in self.getSelectsFilePath():
            if f.endswith('.d'):
                d = self.readDataFile(f)
                if not d:
                    QMessageBox.warning(self, '警告', '数据读取失败\r\n%s'%f, QMessageBox.Yes)
                    return
                data = d['data']
                conf = d['condition']
                x = [float(t[0]) for t in d['data']]
                y = [float(t[1]) for t in d['data']]
                z = [float(t[2]) for t in d['data']]
                tm = [float(t[3]) for t in d['data']]
                ts = [float(t[4]) for t in d['data']]
                # tm = data[3]
                # ts = data[4]
                repeat  = [float('%.4f'%(m/(s+0.00000001))) for m,s in zip(tm,ts)]
                normal = [float('%.4f'%(100*r/max(repeat))) for r in repeat]
                if conf['type'] == 'PDD':
                    axis_x = z
                if conf['type'] == 'OAR':
                    # 修复角度问题
                    if 'angle' in conf:
                        if conf['angle'] == '0' or conf['angle'] == '180':
                            if conf['direction'] == 'G->T' or conf['direction'] == 'T->G':
                                x = y
                            else:
                                x = x
                        if conf['angle'] == '90' or conf['angle'] == '270':
                            if conf['direction'] == 'G->T' or conf['direction'] == 'T->G':
                                x = x
                            else:
                                x = y
                    else:
                        if conf['direction'] == 'G->T' or conf['direction'] == 'T->G':
                            x = y
                    axis_x = x
                axis_y = normal
                x_list.append(axis_x)
                y_list.append(axis_y)
                f_list.append(f.split('/')[-1])
        if x_list and y_list and f_list:
            multiChartDlg= MultiLineDialog()
            multiChartDlg.setWindowIcon(QIcon(':icons/images_rc/multi-chart.png'))
            multiChartDlg.chart.multiLine(x_list,y_list,f_list)
            multiChartDlg.exec()

    def exportMultiExcel(self):
        chartDealDlg = ChartDealWidget()
        chartDealDlg.exportMultiExcel(self.getSelectsFilePath())

    def showMultiLine(self):
        lines = self.TaskTree.getMultiPlotData()
        x_list = []
        y_list = []
        c_list = []
        for l in lines:
            data = l['data']
            conf = l['conf']
            x = data[0]
            y = data[1]
            z = data[2]
            tm = data[3]
            ts = data[4]
            repeat  = [float('%.4f'%(m/(s+0.00000001))) for m,s in zip(tm,ts)]
            normal = [float('%.4f'%(100*r/max(repeat))) for r in repeat]
            if conf['type'] == 'PDD':
                axis_x = z
            if conf['type'] == 'OAR':
                if conf['direction'] == 'G->T' or conf['direction'] == 'T->G':
                    axis_x = y
                else:
                    axis_x = x
            axis_y = normal
            x_list.append(axis_x)
            y_list.append(axis_y)
            c_list.append(
                '%s/%s/%s'
            )
        self.multiLineDlg.chart.multiLine(x_list,y_list,c_list)
        self.multiLineDlg.show()

    def newProject(self):
        """新建项目"""
        if self.createProjectDlg.exec() == QDialog.Accepted:
            path = self.createProjectDlg.proj_path
            name = self.addProject(self.createProjectDlg.proj_path)
            if name:
                self.addProjectItem(name, path)
            QMessageBox.information(self,'提示','创建项目成功!',QMessageBox.Yes)

    def openProject(self):
        """打开项目"""
        fi = QFileDialog()
        fi.setWindowTitle("打开项目")
        fi.setDirectory(self.save_path)
        fi.setFileMode(QFileDialog.DirectoryOnly)
        fi.setOption(QFileDialog.DontUseNativeDialog, True)
        file_view = fi.findChild(QListView, 'listView')
        # 设置可以打开多个文件夹
        if file_view:
            file_view.setSelectionMode(QAbstractItemView.MultiSelection)
        f_tree_view = fi.findChild(QTreeView)
        if f_tree_view:
            f_tree_view.setSelectionMode(QAbstractItemView.MultiSelection)
        if fi.exec():
            path = fi.selectedFiles()
            for p in path:
                name = self.addProject(p)
                if name:
                    self.addProjectItem(name, p)
            self.updateRecetnProject(path)

    def closeProject(self):
        for currentItem in self.selectedItems():
            rootItem = self.getRootItem(currentItem)
            if rootItem:
                for i in range(0,self.topLevelItemCount()):
                    item = self.topLevelItem(i)
                    if item == rootItem:
                        self.takeTopLevelItem(i)
                        del self.projects[item.text(0)]
                        break
                self.header_path = ''
                self.setHeaderLabel('')
            else:
                QMessageBox.warning(self, '错误', '未选择要关闭的项目', QMessageBox.Yes)

    def closeOneProject(self, currentItem):
        rootItem = self.getRootItem(currentItem)
        if rootItem:
            for i in range(0,self.topLevelItemCount()):
                item = self.topLevelItem(i)
                if item == rootItem:
                    self.takeTopLevelItem(i)
                    del self.projects[item.text(0)]
                    break
            self.header_path = ''
            self.setHeaderLabel('')

    def deleteProject(self):
        """删除项目"""
        items = self.selectedItems()
        rootItems = [item for item in self.selectedItems() if not item.parent()]
        rootTexts = ''
        for item in rootItems:
            rootTexts = rootTexts + item.text(0)+'\r\n'
        res = QMessageBox.warning(self, '提示', '删除以下项目?:\r\n%s\r\n警告：将删除项目下的所有数据文件!!!'%rootTexts, QMessageBox.Yes|QMessageBox.No)
        if not res == 65536:
            for item in rootItems:
                path = self.getItemPath(item)
                try:
                    shutil.rmtree(path)
                    self.closeOneProject(item)
                except:
                    QMessageBox.warning(self, '提示', '项目文件已无法删除项目'%rootTexts, QMessageBox.Yes|QMessageBox.No)

    def openRecentProject(self):
        path = self.sender().text().replace('&','')
        name = self.addProject(path)
        if name:
            self.addProjectItem(name, path)
        self.updateRecetnProject([path])

    def updateRecetnProject(self,path):
        # 添加最近配置文件
        def write_recent_config(path):
            path = list(set(path))
            # 写入最近文件到配置文件中
            config = configparser.RawConfigParser()
            config.add_section('recent')
            for i in range(0, len(path)):
                config.set('recent', str(i), str(path[i]))
            with open(config_path, 'w') as configfile:
                config.write(configfile)
        if path:
            config_path = os.getcwd()+'/conf/project.ini'
            # 读取配置文件中最近项目
            config = configparser.ConfigParser()
            config.read(config_path)
            recent = dict(config['recent'])
            # 更新最近项目到配置文件中
            if recent:
                recent_list = [recent[k] for k in recent.keys()]
                for p in path:
                    recent_list.insert(0,p)
                recent_list = recent_list[0:10]
                write_recent_config(recent_list)
            else:
                write_recent_config(path)

    def addProject(self, path):
        """添加项目"""
        _path,name = os.path.split(path)
        if name in self.projects.keys():
            QMessageBox.warning(self, '警告', '项目已打开或已存在同名项目！！！', QMessageBox.Yes)
        else:
            list_file = os.listdir(path)
            data_dir = None
            task_dir = None
            point_proj_file = None
            for file in list_file:
                if file == 'data':
                    if os.path.isdir(os.path.join(path, file)):
                        data_dir=r'%s'%os.path.join(path, file)
                if file == 'task':
                    if os.path.isdir(os.path.join(path, file)):
                        task_dir=r'%s'%os.path.join(path, file)
                if file == '%s.proj'%name:
                    if os.path.isfile(os.path.join(path, file)):
                        point_proj_file =r'%s'%os.path.join(path, file)
            if data_dir and task_dir and point_proj_file:
                self.projects[name] = {
                    'path':path,
                    'data_path':data_dir,
                    'task_path':task_dir,
                    'proj_file':point_proj_file,
                }
                return name
            #  else:
            #  QMessageBox.warning(self, '警告', '项目不合法，无法打开!', QMessageBox.Yes)

    def addProjectItem(self, proj_name='',proj_path=''):
        """添加一个总项目"""
        if proj_name in self.projectItems.keys():
            QMessageBox.information(self,'提示','项目已打开',QMessageBox.Yes)
            return
        item = QTreeWidgetItem([proj_name])
        item.setIcon(0,self.icon['project'])
        file_list = os.listdir(proj_path)
        for f in file_list:
            if f=='task':
                task_item = QTreeWidgetItem([f])
                task_item.setIcon(0,self.icon['task'])
                item.addChild(task_item)
                task_file_list = os.listdir(proj_path+'/'+'task')
                for f in task_file_list:
                    if f.endswith('.t'):
                        _item = QTreeWidgetItem([f])
                        _item.setIcon(0,self.icon['task'])
                        task_item.addChild(_item)
            if f=='data':
                data_item = QTreeWidgetItem([f])
                data_item.setIcon(0,self.icon['data'])
                item.addChild(data_item)
                data_file_list = os.listdir(proj_path+'/'+'data')
                for f in data_file_list:
                    if f.endswith('.d'):
                        _item = QTreeWidgetItem([f])
                        _item.setIcon(0,self.icon['data'])
                        data_item.addChild(_item)
        self.setHeaderLabel(proj_name)
        self.addTopLevelItem(item)
        self.setPath(proj_name)

    def getRootItem(self, item):
        rootItem = item
        while rootItem.parent():
            rootItem = rootItem.parent()
        return rootItem

    def addPddTask(self):
        '''添加pdd任务'''
        if self.header_path:
            self.pddDlg.setWindowTitle('PDD任务添加')
            if self.pddDlg.exec() == QDialog.Accepted:
                conf = self.pddDlg.conf
                file_name = self.addTaskFile(conf)
                if file_name:
                    self.addItem(file_name)
                else:
                    QMessageBox.warning(self,"警告","请选择项目后再添加！",QMessageBox.Yes)

    def addOarTask(self):
        '''添加oar任务'''
        if self.header_path:
            self.oarDlg.setWindowTitle('OAR任务添加')
            if self.oarDlg.exec() == QDialog.Accepted:
                conf = self.oarDlg.conf
                file_name = self.addTaskFile(conf)
                if file_name:
                    self.addItem(file_name)
                else:
                    QMessageBox.warning(self,"警告","请选择项目后再添加！",QMessageBox.Yes)

    def addTaskFile(self, condition):
        """添加测试任务文件

        filename:文件名
        data:  测量数据 [[x,y,z,tm,ts],[x,y,z,tm,ts],....]
        condition:  测量条件 {"type":"PDD"}
        """
        config = configparser.RawConfigParser()
        # 添加condition选项
        config.add_section('condition')
        for k in condition.keys():
            config.set('condition', str(k), str(condition[k]))
        # 文件名称
        t = condition
        ti = time.strftime("%Y%m%d%H%M%S", time.localtime())
        # _hash = self.get_hashlib()
        direction = t['direction'] if 'direction' in t else ''
        angle = t['angle'] if 'angle' in t else ''
        half = t['half'] if 'half' in t else ''
        file_name= '%s_%s_%s_%s_%s_%s_%s_%s.t'%(
            t['ray_type'],
            t['type'],
            t['power'],
            t['ray_size_x']+'x'+t['ray_size_y'],
            direction.replace('->',''),
            angle,
            half,
            ti,)
        if self.currentItem():
            item = self.getRootItem(self.currentItem())
            task_path = self.projects[item.text(0)]['task_path']
            path = r'%s\%s' % (task_path, file_name)
            # 写入并保存文件到当前项目文件夹下
            with open(path, 'w') as configfile:
                config.write(configfile)
            return file_name
        else:
            QMessageBox.warning(self, "错误", "请选择项目再添加任务", QMessageBox.Yes)

    def addDataFile(self, condition={},data=[] ):
        """写入数据到项目文件中

        filename:文件名
        data:  测量数据 [[x,y,z,tm,ts],[x,y,z,tm,ts],....]
        condition:  测量条件 {"type":"PDD"}
        """
        config = configparser.RawConfigParser()
        # config = self.raw_config
        # 添加condition选项
        config.add_section('condition')
        _time      = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime())
        config.set('condition', 'time', _time)
        for k in condition.keys():
            config.set('condition', str(k), str(condition[k]))
        # 添加data选项
        config.add_section('data')
        for i in range(0,len(data)):
            config.set('data', str(i), str(data[i]))
        # 文件名称
        t = condition
        ti = time.strftime("%Y%m%d%H%M%S", time.localtime())
        _hash = self.get_hashlib()
        angle = t['angle'] if 'angle' in t else ''
        half = t['half'] if 'half' in t else ''
        file_name= '%s_%s_%s_%s_%s_%s_%s_%s.d'%(
            t['ray_type'],
            t['type'],
            t['power'],
            t['ray_size_x']+'x'+t['ray_size_y'],
            t['direction'].replace('->','').replace('cm','').replace('Mev',''),
            angle,
            half,
            ti,)
        # path = r'%s\%s' % (self.data_path, file_name)
        # 保存数据文件到正在执行的item对应的项目下
        if self.currentItem():
            item = self.getRootItem(self.runTaskItem)
            task_path = self.projects[item.text(0)]['data_path']
            path = r'%s\%s' % (task_path, file_name)
            # 写入并保存文件到当前项目文件夹下
            with open(path, 'w') as configfile:
                config.write(configfile)
            self.addItem(file_name)
        else:
            QMessageBox.warning(self, "错误", "请选择项目再添加任务", QMessageBox.Yes)

    def chartDeal(self):
        file_list = [item.text(0) for item in self.selectedItems()]
        self.chartDealDlg.treeWidget.addDataItem(file_list)
        self.chartDealDlg.setPath(self.proj_name)
        self.chartDealDlg.exec()

    def deleteSelected(self):
        '''删除选中'''
        file_list = [item.text(0) for item in self.selectedItems()]
        if not QMessageBox.warning(self,'删除确认','确认要删除以下文件么？\r\n%s'%('\r\n'.join(file_list)),QMessageBox.Yes|QMessageBox.No) == 65536:
            for item in self.selectedItems():
                item_parent = item.parent()
                if item.text(0).endswith('.t') or item.text(0).endswith('.d'):
                    item.parent().removeChild(item)
                    # 删除文件
                    file_path = self.proj_save_path+'/'+item_parent.parent().text(0)+'/'+item_parent.text(0)+'/'+item.text(0)
                    os.remove(file_path)
                else:
                    QMessageBox.warning(self,'提示','请选择以.t和.d结尾的文件',QMessageBox.Yes)

    def addItem(self,file_name):
        if self.rootItem:
            for i in range(0,self.rootItem.childCount()):
                _type = ''
                if file_name.endswith('.t'):
                    _type = 'task'
                if file_name.endswith('.d'):
                    _type = 'data'
                if self.rootItem.child(i).text(0)==_type:
                    it = QTreeWidgetItem([file_name])
                    it.setIcon(0,self.icon[_type])
                    self.rootItem.child(i).addChild(it)

    def readTaskFile(self, file_path=''):
        """读取任务文件中数据 """
        # try:
        config = configparser.ConfigParser()
        config.read(file_path)
        condition = dict(config['condition'])
        if condition['type'] == "OAR":
            condition['road'] = json.loads(condition['road'])
            condition['pos_x'] = json.loads(condition['pos_x'])
            condition['pos_y'] = json.loads(condition['pos_y'])
            condition['step_x'] = json.loads(condition['step_x'])
            condition['step_y'] = json.loads(condition['step_y'])
        if condition['type'] == "PDD":
            condition['road'] = json.loads(condition['road'])
            condition['pos'] = json.loads(condition['pos'])
            condition['step'] = json.loads(condition['step'])
        # 根据键值序号排序
        return  condition
        # except:
            # QMessageBox.warning(self, '警告', '文件格式错误，读取失败!', QMessageBox.Yes)

    def readDataFile(self, file_path=''):
        """读取项目文件中数据

        :param file_name: 文件名
        :return:
        """
        try:
            config = configparser.ConfigParser()
            config.read(file_path)
            condition = dict(config['condition'])
            data = dict(config['data'])
            # 根据键值序号排序
            data_list = [[int(k),data[k]] for k in data.keys()]
            data_list = sorted(data_list)
            # 生成最后数据 [['1','2',],[]]
            data_new = [d[1].replace('[', '').replace(']', '').split(',') for d in data_list]
            return {'condition': condition, 'data': data_new}
        except:
            return False

    def markDoneTaskFile(self, index):
        """将执行完的任务进行标记"""
        self.taskItems[index].setIcon(0,QIcon(':icons/images_rc/task-green.png'))
        # 关闭执行任务闪烁
        self.run_task_flag = False

    def markRunTaskFile(self, index):
        """正在执行完的任务进行标记"""
        self.runTaskItem = self.taskItems[index]
        # 打开执行任务闪烁
        self.run_task_flag = True

    def markStopTaskFile(self, index):
        """标记紧急停止的文件"""
        self.taskItems[index].setIcon(0,QIcon(':icons/images_rc/pause-red.png'))
        self.run_task_flag = False

    def markDefaultTaskFile(self):
        """标记所有任务为默认"""
        for item in self.taskItems:
            item.setIcon(0,QIcon(':icons/images_rc/task.png'))

    def runTask(self):
        if self.run_task_flag:
            if self.run_task_status:
                self.run_task_status = False
                self.runTaskItem.setIcon(0,QIcon(':icons/images_rc/circle-green.png'))
            else:
                self.run_task_status = True
                self.runTaskItem.setIcon(0,QIcon(':icons/images_rc/circle-red.png'))

    def getSelectTasks(self):
        """获取选中的任务"""
        # 先将任务列表下的所有任务文件图标更换为默认图标
        for s in self.selectedItems():
            if s.text(0).endswith('.t'):
                parent_item = s.parent()
                for i in range(0,parent_item.childCount()):
                    child_item  = parent_item.child(i)
                    child_item.setIcon(0,QIcon(':icons/images_rc/task.png'))
                break
        # 清除任务执行图标变化标志
        self.run_task_flag = False
        self.run_task_status = False
        # 获取选取的任务，并将选取的任务文件图标进行更换
        items = []
        tasks = []
        for item in self.selectedItems():
            if item.text(0).endswith('.t'):
                item.setIcon(0,QIcon(':icons/images_rc/task-red.png'))
                items.append(item)
                file_path = self.getItemPath(item)
                condition = self.readTaskFile(file_path)
                tasks.append(condition)
        self.taskItems = items
        self.tasks = tasks
        return self.tasks

    def getItemPath(self, item):
        """获取任务文件的路径"""
        if item:
            if item.parent():
                rootItem = item
                item_path = rootItem.text(0)
                while rootItem.parent():
                    rootItem = rootItem.parent()
                    item_path = rootItem.text(0) +'/' + item_path
                item_path = self.projects[rootItem.text(0)]['path']+'/'+item_path.replace(rootItem.text(0)+'/','')
                return item_path
            else:
                rootItem = item
                item_path = self.projects[rootItem.text(0)]['path']
                return item_path
        # item_path = self.save_path+'\\'+item_path

    def get_hashlib(self):
        _str = str(time.time())
        h = hashlib.md5()#md5对象，md5不能反解，但是加密是固定的，就是关系是一一对应，所以有缺陷，可以被对撞出来
        h.update(bytes('%s'%_str,encoding='utf-8'))#要对哪个字符串进行加密，就放这里
        return h.hexdigest()[0:6]#拿到加密字符串

    def tmrChange(self):
        file_list = []
        tmr_conf = []
        tmr_x = []
        tmr_normal = []
        for item in self.selectedItems():
            item_parent = item.parent()
            if item.text(0).endswith('.d'):
                # 删除文件
                file_path = self.proj_save_path+'/'+item_parent.parent().text(0)+'/'+item_parent.text(0)+'/'+item.text(0)
                file_list.append(file_path)
                res = self.readDataFile(file_path)
                if res:
                    conf = res['condition'] if 'condition' in res else None
                    data = res['data'] if 'data' in res else None
                    if conf and data:
                        if conf['type'] == 'PDD':
                            try:
                                tm = [float(d[3]) for d in data]
                                ts = [float(d[4]) for d in data]
                                repeat  = [float('%.4f'%(m/(s+0.00000001))) for m,s in zip(tm,ts)]
                                normal = [float('%.4f'%(100*r/max(repeat))) for r in repeat]
                                tmr_conf.append(conf)
                                tmr_x.append([float(d[2]) for d in data])
                                tmr_normal.append(normal)
                            except ZeroDivisionError as e:
                                QMessageBox.warning(self,'提示','文件数据错误\r\n%s'%e,QMessageBox.Yes)
                                return
                            else:
                                QMessageBox.warning(self,'提示','文件数据错误\r\n%s'%file_path,QMessageBox.Yes)
                        return
                    else:
                        QMessageBox.warning(self,'提示','文件打开失败,转换错误\r\n%s'%file_path,QMessageBox.Yes)
                    return
        if tmr_conf:
            self.getTMR(tmr_x,tmr_normal,tmr_conf)
        else:
            QMessageBox.warning(self,'提示','请选择以 .d 结尾的PDD测量数据文件',QMessageBox.Yes)

    def tmrOpen(self):
        try:
            win32api.ShellExecute(0, 'open', '%s/TMR/pddtotmr.exe'%os.getcwd(), '','',1)
        except:
            QMessageBox.information( self, '提示','打开TMR软件失败，请放入TMR软件至：%s/TMR/pddtotmr.exe'%os.getcwd(), QMessageBox.Yes)

    def getTMR(self,x_list,y_list,c):
        '''选中曲线转换tmr文件'''
        file_path =  QFileDialog.getSaveFileName(self,"导出TMR文件","" ,"tmr_results files (*.tmr_results);;all files(*.*)")
        filename = file_path[0]
        if filename:
            try:
                number = len(x_list)
                with open(filename,'w') as f:
                    mat = "{:^10}{:^4} {:^4}\n"
                    f.write(mat.format(number,c[0]['power'].replace('MeV',''),'%.1f'%float(c[0]['ssd'].replace('cm',''))))
                    n = 0
                    for x,y,c in zip(x_list,y_list,c):
                        # con = c.split(',')
                        raysize = c['ray_size_x'].replace('cm','')
                        mat = "{:^10}{:^10}  {:^2}\n"
                        f.write(mat.format(n,'%.2f'%float(raysize),60))
                        n += 1
                        x = np.array(x)
                        y = np.array(y)
                        xnew= np.arange(x.min(),x.max(),0.5)
                        func = interpolate.interp1d(x, y, kind='slinear')
                        ynew= func(xnew)
                        # ynew = self.aveFilter(ynew,4)
                        for i in range(0,len(xnew)):
                            if xnew[i] > 0 and xnew[i]%5 == 0:
                                mat = "{:^13}  {:^7}\n"
                                f.write(mat.format('%.5f'%(xnew[i]/10.0),'%.5f'%(ynew[i]/100.0)))
                        f.write(mat.format('%.5f'%(30.0),'%.5f'%(ynew[-1]/100.0)))
                QMessageBox.information( self, '提示','导出TMR完成', QMessageBox.Yes)
            except:
                QMessageBox.information( self, '提示','数据错误，导出TMR失败', QMessageBox.Yes)

class ProjectDock(QDockWidget, Ui_DockWidget):
    signal_itemDoubleClickedShow = pyqtSignal(str)
    def __init__(self,parent=None):
        super(ProjectDock, self).__init__(parent)
        self.setupUi(self)
        self.setWindowIcon(QIcon(':icons/images_rc/project.png'))
        self.save_path = os.getcwd()+'\\projects'
        self.setWindowTitle('项目 %s'%self.save_path)
        self.setMinimumHeight(150)
        self.setMinimumWidth(450)
        # 项目目录树
        self.treeWidget = TreeWidget(save_path=self.save_path)
        # 添加控件到界面
        self.verticalLayout.addWidget(self.treeWidget)

class TaskRunManager(QLabel):
    signal = pyqtSignal(str)
    def __init__(self, parent = None):
        super(TaskRunManager, self).__init__(parent)
        # Thread.__init__(self)
        # self.setDaemon(True)
        # 消息推送堆栈
        # self.msg_queue = msg_queue
        # 线程开关
        self.done = False
        # 执行进度
        self.step = 0
        # 任务运行标志
        self.task_running = False
        # 开始运行一次标志
        self.start_run = False
        # 暂停标志
        self.pause_run = False
        self.pause_flag = False
        # 继续标志
        self.continue_run = False
        # 下一个标志
        self.next_run = False
        # 执行任务第一个点
        self.first_pos_run = False
        # 定位执行标志
        self.select_run = False
        self.first_run = False
        # 移动到第一个点标志
        self.move_to_first_flag = False
        # 移动边测量标志
        self.move_measure_flag = False

    def running(self):
        if not self.done:
            if self.start_run:  # 执行一次
                self.start_run = False
                if self.pause_run:  # 暂停
                    self.pause_run = False
                    # 标记暂停
                    self.pause_flag = True
                    self.signal.emit("PAUSE")
                    # 关闭移动到第一个点标志
                    self.move_to_first_flag = False
                else:
                    self.task_running = True
                    # if self.step < len(self.task):
                    if self.continue_run:  # 继续执行
                        self.continue_run = False
                        self.signal.emit("CONTINUE")
                    if self.select_run:  # 选择位置处执行任务
                        self.select_run = False
                        self.signal.emit("SELECT")
                    if self.first_run:  # 第一个任务开始执行
                        self.first_run = False
                        self.signal.emit("FIRST")
                    if self.next_run:  # 执行下一个任务
                        self.next_run = False
                        self.signal.emit("NEXT")
                    if self.first_pos_run:  # 移动到第一个点
                        self.first_pos_run = False
                        self.signal.emit("MOVE_FIRST")
                        self.move_to_first_flag = True

    def startRun(self):
        " 开始执行"
        self.start_run = True

    def firstRun(self):
        "第一个位置处执行"
        self.start_run = True
        self.first_run = True

    def selectRun(self):
        "选择处执行"
        self.start_run = True
        self.select_run = True

    def pauseRun(self):
        "暂停"
        self.start_run = True
        self.pause_run = True

    def continueRun(self):
        "继续"
        self.start_run = True
        self.continue_run = True

    def moveToFirstPos(self):
        "移动到第一个点位置"
        self.start_run = True
        self.first_pos_run = True

    def nextRun(self):
        "开始下一个任务"
        self.start_run = True
        self.next_run = True
        self.step += 1

    def clearFlag(self):
        "清空标志"
        self.step = 0
        self.task_running = False
        self.start_run = False
        self.pause_run = False
        self.pause_flag = False
        self.continue_run = False
        self.next_run = False
        self.first_pos_run = False
        self.select_run = False
        self.first_run = False
        self.move_to_first_flag = False
        self.move_measure_flag = False

if __name__ == '__main__':
    import sys
    app = QApplication(sys.argv)
    win = ProjectDock()

    condition = {'ssd': '100cm', 'ray_size_x': '10cm', 'type': 'PDD', 'deepth': '60mm', 'name': '基地加速器', 'time': '2018-11-14 17:21:23', 'power': '8MeV', 'ray_size_y': '10cm', 'room': '001', 'direction': 'O->G', 'ray_type': '电子'}
    data = [[0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0], [0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0], [0.0, 1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0, 9.0, 10.0, 11.0, 12.0, 13.0, 14.0, 15.0, 16.0, 17.0, 18.0, 19.0, 20.0, 21.0, 22.0, 23.0, 24.0, 25.0, 26.0, 27.0, 28.0, 29.0, 30.0, 40.0, 50.0, 60.0], [44280.0, 43566.0, 43743.0, 42114.0, 41300.0, 43563.0, 47083.0, 46582.0, 47387.0, 47537.0, 47123.0, 47029.0, 47984.0, 49199.0, 50073.0, 49323.0, 51662.0, 51287.0, 48107.0, 50043.0, 50942.0, 50346.0, 47379.0, 46627.0, 45215.0, 42911.0, 40629.0, 38665.0, 35755.0, 34396.0, 31635.0, 6867.0, 1150.0, 1129.0], [15174.0, 14962.0, 15029.0, 14500.0, 14251.0, 14478.0, 15179.0, 14850.0, 14953.0, 14860.0, 14578.0, 14408.0, 14575.0, 14810.0, 14967.0, 14684.0, 15306.0, 15203.0, 14315.0, 14970.0, 15377.0, 15400.0, 14753.0, 14871.0, 14849.0, 14599.0, 14413.0, 14393.0, 14072.0, 14456.0, 14327.0, 14226.0, 14292.0, 15354.0]]



    t = condition
    ti = time.strftime("%Y%m%d%H%M%S", time.localtime())
    file_name= '%s_%s_%s_%s_%s_%s'%(
        t['type'],
        t['ray_type'],
        t['power'],
        t['ray_size_x'],
        t['direction'].replace('->',''),
        ti,)

    x = data[0]
    y = data[1]
    z = data[2]
    tm = data[3]
    ts = data[4]
    data = [[h,i,j,k,l] for h,i,j,k,l in zip(x,y,z,tm,ts)]

    win.writeFile(file_name,t,data)
    win.show()
    app.exec_()
